<template>
  <div>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>收藏列表</span>
        </div>
      </template>

      <div>
        <el-form inline>
          <el-form-item label="房源">
            <el-autocomplete
              v-model="searchForm.title"
              :fetch-suggestions="querySearchHomestay"
              clearable
              class="inline-input w-50"
              @select="searchSelectHomestay"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="客户">
            <el-autocomplete
              v-model="searchForm.username"
              :fetch-suggestions="querySearchUsername"
              clearable
              class="inline-input w-50"
              @select="searchSelectUsername"
              placeholder="请输入"
            />
          </el-form-item>
        </el-form>
        <div
          style="
            width: 100%;
            padding-bottom: 20px;
            display: flex;
            justify-content: flex-end;
          "
        >
          <el-button type="primary" @click="searchSubmit">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>

      <VTable
        :tableData="tableData"
        :options="options"
        @getSelection="handleSelection"
      >
        <template #menubtn>
          <el-button type="primary" @click="handleAdd">新增</el-button>
          <el-button type="warning" @click="handleBatchDelete"
            >批量删除</el-button
          >
        </template>

        <template #operate="scope">
          <el-button
            size="small"
            link
            type="danger"
            :icon="Delete"
            @click="handleDelete(scope.row.id)"
            >删除</el-button
          >
        </template>
      </VTable>

      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        style="width: 600px"
        @close="resetForm(ruleFormRef)"
      >
        <el-form
          v-if="actionType === '新增'"
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="auto"
        >
          <el-form-item
            v-for="item in filterOptions"
            :key="item"
            :label="item.label"
            :prop="item.prop"
          >
            <el-autocomplete
              v-if="item.prop === 'title'"
              v-model="ruleForm[item.prop]"
              :fetch-suggestions="querySearchHomestay"
              clearable
              class="inline-input w-50"
              @select="handleSelectHomestay"
            />
            <el-autocomplete
              v-else-if="item.prop === 'username'"
              v-model="ruleForm[item.prop]"
              :fetch-suggestions="querySearchUsername"
              clearable
              class="inline-input w-50"
              @select="handleSelectUsername"
            />
            <!-- <el-input v-model="ruleForm[item.prop]"></el-input> -->
          </el-form-item>
        </el-form>

        <template #footer>
          <el-button @click="resetForm(ruleFormRef)">关闭</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            确定
          </el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import VTable from "../../components/VTable/index.vue";
import { onMounted, ref, reactive } from "vue";
import {
  getAllCollect,
  deleteCollect,
  batchDeleteCollect,
  addCollect,
  searchCollect,
} from "../../api/collectManage/index";
import { Loading } from "element-plus/es/components/loading/src/service";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import { Delete, Edit, View, Plus, List } from "@element-plus/icons-vue";
import { getUserList, searchUser } from "../../api/userManage/index";
import {
  getAllHomestay,
  searchHomestayByTitle,
} from "../../api/homestayManage/index";
const tableData = ref<any>([]);
const options = [
  {
    prop: "username",
    label: "用户",
    isTable: true,
    isForm: true,
  },
  {
    prop: "title",
    label: "房源",
    isTable: true,
    isForm: true,
  },
  {
    prop: "photos",
    label: "图片",
    isTable: true,
    type: "images",
  },
  {
    prop: "createTime",
    label: "创建时间",
    isTable: true,
    type: "time",
  },
];
const filterOptions = options.filter((item) => item.isForm == true);

const dialogTitle = ref("查看"); // 弹出层标题
const dialogVisible = ref<boolean>(false);
const actionType = ref(""); // 操作按钮的类型
const setDialogTile = (type: string) => {
  dialogTitle.value = type;
  actionType.value = type;
  dialogVisible.value = true;
};

//新增
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  title: [{ required: true, message: "请输入房源", trigger: "blur" }],
});
let ruleForm = reactive({
  userId: Number,
  houseId: Number,
});
const handleAdd = () => {
  setDialogTile("新增");
};
//自动补全
const querySearchUsername = async (name, callback) => {
  const list = [];
  if (name) {
    const res = await searchUser({ username: name });
    res.data.data.forEach((item) => {
      list.push({ value: item.username, id: item.id });
    });
  } else {
    const res = await getUserList();
    res.data.data.forEach((item) => {
      list.push({ value: item.username, id: item.id });
    });
  }
  callback(list);
};
const querySearchHomestay = async (name, callback) => {
  const list = [];
  if (name) {
    const res = await searchHomestayByTitle({ title: name });
    res.data.data.forEach((item) => {
      list.push({ value: item.title, id: item.id });
    });
  } else {
    const res = await getAllHomestay();
    res.data.data.forEach((item) => {
      list.push({ value: item.title, id: item.id });
    });
  }
  callback(list);
};
//选中
const handleSelectUsername = (item, $event) => {
  console.log(item);
  ruleForm.userId = item.id;
};
const handleSelectHomestay = (item, $event) => {
  console.log(item);
  ruleForm.houseId = item.id;
};

//关闭
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogVisible.value = false;
};

//提交
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  console.log("ruleForm", ruleForm);
  const res = await addCollect(ruleForm);
  if (res.data.success == true) {
    ElMessage({
      message: res.data.msg,
      type: "success",
    });
  } else {
    ElMessage.error(res.data.msg);
  }
  onLoad();
  dialogVisible.value = false;
};

//搜索
const searchForm = ref<any>({
  username: "",
  title: "",
  userId: "",
  houseId: "",
});
const searchSubmit = async () => {
  console.log("searchForm", searchForm.value);
  const res = await searchCollect(searchForm.value);
  tableData.value = res.data.data;
};
//重置
const resetSearch = async () => {
  searchForm.value = {
    username: "",
    title: "",
    userId: "",
    houseId: "",
  };
  await onLoad();
};
//搜索选中
const searchSelectUsername = (item, $event) => {
  console.log(item);
  searchForm.value.userId = item.id;
};
const searchSelectHomestay = (item, $event) => {
  console.log(item);
  searchForm.value.houseId = item.id;
  console.log();
};

//删除
const handleDelete = async (id: number) => {
  ElMessageBox.confirm("确认删除此项数据?", "系统提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      console.log(id);
      const res = await deleteCollect(id);
      if (res.data.success == true) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
      } else {
        ElMessage.error(res.data.msg);
      }
      await onLoad();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

//子组件传值--多选
const ids = ref<any>([]);
const handleSelection = (val: any) => {
  const selecction: any = [];
  val.forEach((item: any) => {
    selecction.push(item.id);
  });
  ids.value = selecction;
  console.log("ids.value:", ids.value);
};
// 批量删除
const handleBatchDelete = async () => {
  if (ids.value.length == 0) {
    ElMessage({
      type: "info",
      message: "请选择数据",
    });
    return;
  }
  ElMessageBox.confirm("确认删除这些数据?", "系统提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await batchDeleteCollect(ids.value);
      if (res.data.success) {
        ElMessage({
          message: res.data.msg,
          type: "success",
        });
      } else {
        ElMessage.error(res.data.msg);
      }
      onLoad();
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

const onLoad = async () => {
  const res = await getAllCollect();
  tableData.value = res.data.data;
  console.log(tableData.value);
};
onMounted(async () => {
  await onLoad();
});
</script>

<style></style>
